//vector3偏移
export function vector3Offset(point, { offsetX = 0, offsetY = 0, offsetZ = 0 }) {
	let scene = window.viewer.scene;
	let globe = scene.globe;
	let vec3 = Li.Vector3.create(offsetX, offsetY, offsetZ);
	let localToWorld = globe.ellipsoid.eastNorthUpToFixedFrame(point.toCartesian3());
	let newPoint = Li.Matrix4.multiplyByVector3(localToWorld, vec3);
	return newPoint;
}
// JSON转Vector3
export function jsonToVec3(list, cb) {
	let isArray = Array.isArray(list);
	list = isArray ? list : [list];
	let points = [];
	list.forEach((item) => {
		let vec3;
		if (Array.isArray(item)) {
			let carto = SSmap.Cartographic.fromDegrees(item[0], item[1], item[2] || 0);
			vec3 = carto.toVector3();
		} else if (item.x) {
			vec3 = SSmap.Vector3.create(item.x, item.y, item.z);
		} else {
			vec3 = SSmap.Cartographic.fromDegrees(Number(item.longitude), Number(item.latitude), Number(item.height)).toVector3();
		}
		points.push(vec3);
	});
	const result = isArray ? points : points[0];
	cb && cb(JSON.stringify(result));
	return result;
}
/**
 * vector3转cartographic
 * @param {*} list vector3 or vectorArray
 * @param {*} isDegrees 是否转角度
 * @returns Cartographic or CartographicArray
 */
export function vec3ToCarto(list, isDegrees) {
	let isArray = Array.isArray(list);
	list = isArray ? list : [list];
	let points = [];
	list.forEach((item) => {
		let carto = item.toCartographic();
		if (isDegrees) {
			carto = carto.toDegrees();
		}
		points.push(carto);
	});
	return isArray ? points : points[0];
}
export function getCameraPosition(cb) {
	let scene = GlobalViewer.scene;
	let camera = scene.mainCamera;
	let cameraController = camera.cameraController();
	let position = cameraController.positionWC;
	let radian = Math.PI / 180;
	let degrees = position.toCartographic().toDegrees();
	let object = {
		position: {
			x: 0,
			y: 0,
			z: 0,
		},
		degrees: {
			longitude: 0,
			latitude: 0,
			height: 0,
		},
		heading: 0,
		pitch: 0,
		roll: 0,
		time: 2,
	};

	object.heading = cameraController.heading / radian;
	object.pitch = cameraController.pitch / radian;
	object.roll = cameraController.roll / radian;
	object.position.x = position.x;
	object.position.y = position.y;
	object.position.z = position.z;
	object.degrees.longitude = degrees.longitude;
	object.degrees.latitude = degrees.latitude;
	object.degrees.height = degrees.height;
	cb && cb(object);

	return object;
}
export function cartoToArray(list) {
	let isArray = Array.isArray(list);
	list = isArray ? list : [list];
	let points = [];
	list.forEach((item) => {
		let arr = [];
		arr.push(item.longitude);
		arr.push(item.latitude);
		arr.push(item.height);
		points.push(arr);
	});
	return isArray ? points : points[0];
}

export function jsonToCar3(list) {
	let isArray = Array.isArray(list);
	list = isArray ? list : [list];
	let points = [];
	list.forEach((item) => {
		let vec3 = Li.Cartesian3.create(item.x, item.y, item.z);
		points.push(vec3);
	});
	return isArray ? points : points[0];
}
export function jsonToCar3FromDegrees(list) {
	let isArray = Array.isArray(list);
	list = isArray ? list : [list];
	let points = [];
	list.forEach((item) => {
		let Cartesian3 = Li.Cartesian3.fromDegrees(item.longitude, item.latitude, item.height);
		points.push(Cartesian3);
	});
	return isArray ? points : points[0];
}
// Vector3转JSON
export function vec3ToJson(points) {
	let isArray = Array.isArray(points);
	points = isArray ? points : [points];
	let list = [];
	points.forEach((item) => {
		let obj = {};
		obj.x = item.x;
		obj.y = item.y;
		obj.z = item.z;
		list.push(obj);
	});
	return isArray ? list : list[0];
}
// Cartesian3转JSON
export function CartographicToJson(points) {
	let isArray = Array.isArray(points);
	points = isArray ? points : [points];
	let list = [];
	points.forEach((item) => {
		let obj = {};
		obj.longitude = item.longitude;
		obj.latitude = item.latitude;
		obj.height = item.height;
		list.push(obj);
	});
	return isArray ? list : list[0];
}
// vec3转Cartesian3
export function vec3ToCartesian(points) {
	let isArray = Array.isArray(points);
	points = isArray ? points : [points];
	let list = [];
	points.forEach((item) => {
		let cartesian = Li.Vector3.create(item.x, item.y, item.z).toCartesian3();
		list.push(cartesian);
	});
	return isArray ? list : list[0];
}
//拾取地面坐标
export function pickGlobePoint(x, y, includeTerrainSurface) {
	let scene = window.viewer.scene;
	let globe = scene.globe;
	let ray = scene.mainCamera.screenPointToRay(x, y);
	let pickPos = Li.Cartesian3.create(0, 0, 0);
	let ret = globe.pick(ray, pickPos);
	if (ret) {
		//高程数据
		if (includeTerrainSurface) {
			let carto = Li.Cartographic.fromCartesian(pickPos);
			let h = globe.getHeight(carto, true);
			carto.height = h;
			return carto.toCartesian3();
		}

		return pickPos;
	}
	return Li.Cartesian3.create(0, 0, 0);
}
//通过鼠标拾取世界坐标 （Vector3）
export function pickWorldPositionByMouse(x, y, cb) {
	let scene = GlobalViewer.scene;
	let ray = scene.mainCamera.screenPointToRay(x, y);
	let hit = new SSmap.RaycastHit();
	let point = null;
	if (scene.raycast(ray, hit)) {
		point = hit.point; //Vector3
		//客户端不能直接使用hit.point,重新拷贝一次
		point = SSmap.Vector3.create(point.x, point.y, point.z);
	}
	if (point) calcWorldLonAndLat(point);
	hit.delete();
	cb && cb(point);
	return point;
}
// UI层使用
export function clickToWorldPosition(screenPoint, cb) {
	let scene = GlobalViewer.scene;
	let ray = scene.mainCamera.screenPointToRay(screenPoint.x, screenPoint.y);
	let hit = new SSmap.RaycastHit();
	let point = null;
	if (scene.raycast(ray, hit)) {
		point = hit.point; //Vector3
		//客户端不能直接使用hit.point,重新拷贝一次
		point = SSmap.Vector3.create(point.x, point.y, point.z);
	}
	hit.delete();
	cb && cb(vec3ToJson(point));
}
//  通过鼠标拾取世界坐标 （longitude，latitude，height）
export function pickWorldPositionGetDefrees(x, y, cb) {
	let scene = GlobalViewer.scene;
	let ray = scene.mainCamera.screenPointToRay(x, y);
	let hit = new SSmap.RaycastHit();
	let point = null;
	if (scene.raycast(ray, hit)) {
		point = hit.point.toCartesian3().toCartographic().toDegrees(); //Degrees
	}
	cb &&
		cb({
			longitude: point.longitude,
			latitude: point.latitude,
			height: point.height,
		});
}

export function calcWorldLonAndLat(position, callback) {
	let vec3 = Li.Vector3.create(position.x, position.y, position.z);
	let deg = vec3.toCartesian3().toCartographic().toDegrees();
	callback &&
		callback({
			longitude: deg.longitude,
			latitude: deg.latitude,
			height: deg.height,
		});
}
export function pickPointToJson(e, cb) {
	let scene = window.viewer.scene;
	let ray = scene.mainCamera.screenPointToRay(e.x, e.y);
	let hit = new Li.RaycastHit();
	let point = null;
	if (scene.raycast(ray, hit)) {
		point = hit.point;
		if (e.type == 'vec3') {
			point = {
				x: point.x,
				y: point.y,
				z: point.z,
			};
		} else {
			point = Li.Vector3.create(point.x, point.y, point.z);
			point = point.toCartographic().toDegrees();
			point = {
				longitude: point.longitude,
				latitude: point.latitude,
				height: point.height,
			};
		}
	}
	cb(point);
	hit.delete();
}
/**
 * 颜色格式转换
 * @param {string} colorString - 颜色字符串。
 * @returns {string} - rbga格式颜色字符串
 */
export function convertColorFormat(colorString) {
	let result;

	// 移除字符串中的空格
	colorString = colorString.replace(/\s/g, '');

	// 如果是 #RRGGBB 或 #RRGGBBAA 格式
	const hexMatch = colorString.match(/^#(?:([0-9a-fA-F]{3}){1,2}|([0-9a-fA-F]{4}){1,2})$/);
	if (hexMatch) {
		const hexValue = hexMatch[0].substring(1); // 去掉 #

		result = {
			r: parseInt(hexValue.substring(0, 2), 16),
			g: parseInt(hexValue.substring(2, 4), 16),
			b: parseInt(hexValue.substring(4, 6), 16),
			a: hexValue.length === 8 ? parseInt(hexValue.substring(6, 8), 16) : 255,
		};

		return result;
	}

	// 如果是 rgba(R, G, B, A) 格式
	const rgbaMatch = colorString.match(/^rgba\((\d+),\s*(\d+),\s*(\d+),\s*([01](\.\d+)?)\)$/);
	if (rgbaMatch) {
		result = {
			r: parseInt(rgbaMatch[1], 10),
			g: parseInt(rgbaMatch[2], 10),
			b: parseInt(rgbaMatch[3], 10),
			a: Math.round(parseFloat(rgbaMatch[4]) * 255),
		};
		return result;
	}

	// 如果是 rgb(R, G, B) 格式
	const rgbMatch = colorString.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/);
	if (rgbMatch) {
		result = {
			r: parseInt(rgbMatch[1], 10),
			g: parseInt(rgbMatch[2], 10),
			b: parseInt(rgbMatch[3], 10),
			a: 255,
		};
		return result;
	}

	// 如果无法匹配任何格式，返回 undefined
	return result;
}
export function pickHitAndRay(x, y) {
	let scene = window.viewer.scene;
	//相机在鼠标点的射线
	let ray = scene.mainCamera.screenPointToRay(x, y);
	//新建射线碰撞对象
	let hit = new Li.RaycastHit();
	//raycast 拾取物体
	if (scene.raycast(ray, hit) && hit.point) {
		return { hit: hit, ray: ray };
	}
}
// 两个点形成一个矩阵，取四个角的坐标

export function creatRayToHit(origin, direction) {
	let subtractdiff = direction.normalize(); //标准化
	let newsubtractdiff = SSmap.Vector3.multiplyByScalar(subtractdiff, 1);
	let newstartpoint = SSmap.Vector3.add(origin, newsubtractdiff);
	let ray = SSmap.Ray.create(newstartpoint, subtractdiff);
	let hit = new SSmap.RaycastHit(); //射线投影
	let rayok = window.viewer.scene.raycast(ray, hit); //判断是否存在 对象和相交位置
	if (rayok && hit.point) {
		return { hit: hit, ray: ray };
	}
}
export function getNSEW(start, end) {
	let extent = Li.Rectangle.create(0, 0, 0, 0);
	extent.combinePoint(start);
	extent.combinePoint(end);
	let sw = extent.southwest().toVector3();
	let nw = extent.northwest().toVector3();
	let ne = extent.northeast().toVector3();
	let se = extent.southeast().toVector3();
	let points = [];
	points.push(sw);
	points.push(nw);
	points.push(ne);
	points.push(se);
	return points;
}

//空间坐标点转换屏幕坐标点
export function worldToScreenPoint(position) {
	let scene = window.viewer.scene;
	let point = scene.mainCamera.worldToScreenPoint(jsonToVec3(position));
	let z = point.z;
	// z值不在-1~1之间的值无效，x、y改成一个很大的值
	if (z < -1 || z > 1) {
		point.x = -999999;
		point.y = -999999;
	}
	return point;
}
// 弧度转角度
export function toDegrees(radians) {
	return (180 / Math.PI) * radians;
}
export const FrameAction = {
	_frameAction: null,
	_events: [],
	add(options, cb) {
		options.cullDistance = options.cullDistance || { min: 0, max: 20000 };
		if (!options.id) {
			throw new Error('FrameAction.add缺少id参数');
		}
		if (!options.offset) {
			options.offset = { x: 0, y: -40 };
		}
		if (!options.handler) {
			options.handler = cb;
		}
		this._events.push(options);
		if (!this._frameAction) {
			let frameAction = new SSmap.FrameAction();
			frameAction.onTriggered(() => {
				this._events.forEach((options) => {
					if (options.list) {
						options.list = Array.isArray(options.list) ? options.list : [options.list];
						options.list.forEach((item) => {
							let point = this.worldToScreenPoint(item.position || item, options.cullDistance);
							item.left = point.x + options.offset.x;
							item.top = point.y + options.offset.y;
						});
						options.handler(options.list);
					} else {
						options.handler();
					}
				});
			});
			GlobalViewer.scene.rootEntity.addComponent(frameAction);
			this._frameAction = frameAction;
		}
	},
	update(options) {
		this._events.forEach((object) => {
			if (object.id == options.id) {
				for (const key in options) {
					object[key] = options[key];
				}
			}
		});
	},
	remove(id) {
		let key = this._events.findIndex((object) => {
			return object.id == id;
		});
		if (key >= 0) {
			this._events.splice(key, 1);
		}
	},
	removeAll() {
		if (this._frameAction) {
			this._frameAction.delete();
			this._frameAction = null;
			this._events.length = 0;
		}
	},
	worldToScreenPoint(object, cullDistance) {
		let position;
		if (Array.isArray(object)) {
			position = SSmap.Cartographic.fromDegrees(object[0], object[1], object[2] || 0);
			position = position.toVector3();
		} else if (typeof object == 'object') {
			position = SSmap.Vector3.create(object.x, object.y, object.z);
		} else {
			position = SSmap.Vector3.create(0, 0, 0);
		}
		let scene = GlobalViewer.scene;
		let point = scene.mainCamera.worldToScreenPoint(position);
		let cameraCtrl = scene.mainCamera.cameraController();
		let height = cameraCtrl.positionCartographic.height;
		let z = point.z;
		// z值不在-1~1之间的值无效，x、y改成一个很大的值
		if (z < -1 || z > 1 || height < cullDistance.min || height > cullDistance.max) {
			point.x = -9999;
			point.y = -9999;
		}
		return point;
	},
};
export function addGeoJsonLayerModel(opt) {
	opt = opt || {};
	let url = window.document.location.href;
	let baseUrl = url.substring(0, url.lastIndexOf('/') + 1);
	var GeoJsonLayerModel = new SSmap.GeoJsonGifLayer();
	GeoJsonLayerModel.gifUrl = baseUrl + opt.iconurl;
	GeoJsonLayerModel.selectedIconUrl = baseUrl + opt.selectediconurl; //
	GeoJsonLayerModel.iconSize = SSmap.Vector2.create(opt.iconwidth, opt.iconheight); //图标大小
	GeoJsonLayerModel.labelOffset = SSmap.Vector2.create(opt.labeloffsetx, opt.labeloffsety); //x, y偏移值
	GeoJsonLayerModel.iconOffset = SSmap.Vector2.create(opt.iconoffsetx, opt.iconoffsety);
	GeoJsonLayerModel.scaleByDistance = SSmap.Vector2.create(opt.scaleDistance[0], opt.scaleDistance[1]);
	GeoJsonLayerModel.clustered = opt.clustered == undefined ? true : opt.clustered;
	GeoJsonLayerModel.height = opt.height; //高度
	GeoJsonLayerModel.lineToGround = opt.lineToGround; //垂线显示
	GeoJsonLayerModel.lineColor = opt.lineColor; //垂线显示
	GeoJsonLayerModel.highlight = opt.highlight; //高度
	GeoJsonLayerModel.labelField = opt.labelfield || ''; //标签
	GeoJsonLayerModel.addField('id'); //添加index索引id
	// GeoJsonLayerModel.addField("进出类型"); //添加字段
	// GeoJsonLayerModel.addField("卡口"); //添加字段
	if (opt.geojsonurl) {
		GeoJsonLayerModel.load(baseUrl + opt.geojsonurl); //加载GeoJson文件的url
	}
	GeoJsonLayerModel.replace = opt.replace == undefined ? true : opt.replace; //true为替换，false为叠加
	//or addString可通过字符串类型数据加载
	if (opt.testString) {
		GeoJsonLayerModel.addString(opt.testString);
	}
	if (window.nowTileset) {
		GeoJsonLayerModel.setBase3DTileset(window.nowTileset.tileset());
	}

	return GeoJsonLayerModel;
}
//数据转换成FeatureCollection格式
export function object2Geojson(data) {
	var featureCollection = { type: 'FeatureCollection' };
	var features = new Array();

	for (let i = 0; i < data.length; i++) {
		var feature = { type: 'Feature' };
		feature.properties = data[i];
		feature.properties.id = i + 1;
		var geometry = { type: 'Point' };
		geometry.coordinates = [data[i].longitude, data[i].latitude];
		feature.geometry = geometry;
		features.push(feature);
	}
	featureCollection.crs = {
		type: 'name',
		properties: {
			name: 'urn:ogc:def:crs:EPSG::4490',
		},
	};
	featureCollection.features = features;
	return JSON.stringify(featureCollection);
}
//添加模型
export function addModelLayer(url, carto, rotation, offset, scale) {
	let modelLayer = new SSmap.ModelLayer(); //将来会停用，慎用
	modelLayer.url = url;
	modelLayer.cartographic = carto;
	modelLayer.rotation = rotation;
	modelLayer.distance = SSmap.Vector2.create(1, 3000);
	modelLayer.offset = offset;
	if (scale) {
		//不设置，默认时为1
		modelLayer.scale = scale;
	}
	modelLayer.componentComplete();
	return modelLayer;
}
export function addPolyline(opt) {
	let url = window.document.location.href;
	let baseUrl = url.substring(0, url.lastIndexOf('/') + 1);

	var polyline = new SSmap.Polyline3D();
	polyline.setWidth(opt.width);
	polyline.alpha = opt.alpha >= 1 ? 0.99 : opt.alpha; //alpha透明度不能设置为1.0
	for (var i = 0; i < opt.pointArr.length; i++) {
		polyline.addPoint(opt.pointArr[i]);
	}
	polyline.color = opt.color;
	polyline.depthTest = opt.depthTest == undefined ? true : opt.depthTest; //是否关闭深度检测
	polyline.setAltitudeMethod(opt.altitudemethod);
	//polyline.setSceneMode(SSmap.TextureProjectionSceneMode.WholeScene);
	if (opt.altitude) {
		polyline.setAltitude(opt.altitude);
	}
	polyline.setMinDistance(5.0); //设定插点的最小距离
	polyline.setGlowMaterial(opt.glow == undefined ? false : opt.glow); //发光
	if (opt.imgurl) {
		polyline.setImageUrl(baseUrl + opt.imgurl);
		polyline.setRepeat(opt.repeat || 20); //纹理动画的重复数量(箭头一类动画)
	}
	if (opt.flowanim) {
		polyline.animationRun = opt.flowanim; //动画
		polyline.animationTimer = opt.flowanimspeed || 3000; //动画 3000ms
	}

	polyline.name = opt.name;
	if (opt.id) {
		polyline.id = opt.id;
		polyline.addProperty('id', opt.id); //拾取 属性设置
		polyline.addProperty('name', opt.name);
	}
	if (opt.twinkletype) {
		polyline.animationType = opt.twinkletype;
	}
	polyline.draw();
	polyline.end();
	return polyline;
}
//xyz转屏幕坐标
export function fromDegreesPm(point) {
	let coordinate = SSmap.Cartesian3.fromDegrees(point.x, point.y, point.z);
	let vector = coordinate.toVector3();
	return vector;
}

//获取包围盒
export function calculateBoundingBox(points) {
	let west = points[0][0];
	let east = points[0][0];
	let south = points[0][1];
	let north = points[0][1];

	for (let i = 1; i < points.length; i++) {
		const longitude = points[i][0];
		const latitude = points[i][1];

		if (longitude < west) {
			west = longitude;
		}
		if (longitude > east) {
			east = longitude;
		}
		if (latitude < south) {
			south = latitude;
		}
		if (latitude > north) {
			north = latitude;
		}
	}

	return {
		west: west,
		east: east,
		south: south,
		north: north,
	};
}
// 扩大包围盒
export function expandBoundingBox(boundingBox, percentage) {
	let west = boundingBox.west;
	let east = boundingBox.east;
	let south = boundingBox.south;
	let north = boundingBox.north;

	// 计算包围盒的宽度和高度
	let width = east - west;
	let height = north - south;

	// 计算扩大后的偏移量
	let offsetX = (width * percentage) / 2;
	let offsetY = (height * percentage) / 2;

	// 扩大包围盒
	let expandedBoundingBox = {
		west: west - offsetX,
		east: east + offsetX,
		south: south - offsetY,
		north: north + offsetY,
	};

	return expandedBoundingBox;
}

export function getCirclePositionByCenterAndRadius(center, radius) {
	let positionList = [];
	radius = radius || 1;
	if (center) {
		let webMercatorProjection = new SSmap.WebMercatorProjection(window.viewer.scene.globe.ellipsoid);
		let centerPosition = SSmap.Cartesian3.fromDegrees(center[0], center[1], center[2]);
		let viewPointWebMercator = webMercatorProjection.project(SSmap.Cartographic.fromCartesian(centerPosition)); // Cartesian3

		for (let i = 0; i <= 360; i++) {
			// 计算目标点
			let toPoint = SSmap.Cartesian3.create(
				viewPointWebMercator.x + radius * Math.cos((i * Math.PI) / 180),
				viewPointWebMercator.y + radius * Math.sin((i * Math.PI) / 180),
				viewPointWebMercator.z
			);
			// 投影坐标转世界坐标
			toPoint = webMercatorProjection.unproject(toPoint);
			toPoint = toPoint.toCartesian3().toCartographic().toDegrees();
			let height = toPoint.height < 0 ? 1 : toPoint.height;
			positionList.push([toPoint.lon, toPoint.lat, height]);
		}
	}
	return positionList;
}

/**
 * 合并参数
 * @param {Object} target -目标对象
 * @param {Object} from -合并的对象
 * @returns {Object}
 * @private
 */
export function mergeOptions(target, from) {
	if (!from) return target;
	let keys = Object.keys(from);
	for (let i = 0; i < keys.length; i++) {
		let key = keys[i];
		if (isPlainObject(from[key])) {
			target[key] = mergeOptions(target[key] || {}, from[key]);
		} else {
			target[key] = from[key];
		}
	}
	return target;
}

/**
 * 判断new Object()生成的对象
 * @param {Object} obj -数据类型Object
 * @returns {Boolean}
 * @private
 */
export function isPlainObject(obj) {
	let toString = Object.prototype.toString;
	let hasOwn = Object.prototype.hasOwnProperty;
	if (toString.call(obj) !== '[object Object]') {
		return false;
	}
	if (obj.constructor && !hasOwn.call(obj.constructor.prototype, 'isPrototypeOf')) {
		return false;
	}
	return true;
}

// 根据pointArray计算中心点
export function getCenterPoint(pointArray) {
	let lonlist = [];
	let latlist = [];
	let heightList = [];
	pointArray.forEach((item) => {
		let point = item.toCartographic().toDegrees();
		lonlist.push(point.longitude);
		latlist.push(point.latitude);
		heightList.push(point.height);
	});
	let minlon = Math.min(...lonlist);
	let maxlon = Math.max(...lonlist);
	let minlat = Math.min(...latlist);
	let maxlat = Math.max(...latlist);
	let minHeight = Math.min(...heightList);
	let maxHeight = Math.max(...heightList);
	let longitude = (minlon + maxlon) / 2;
	let latitude = (minlat + maxlat) / 2;
	let height = (minHeight + maxHeight) / 2;
	let point = SSmap.Cartographic.fromDegrees(longitude, latitude, height);
	return point.toVector3();
}
export function vector3ToDegrees(position, cb) {
	let vector3 = SSmap.Vector3.create(position.x, position.y, position.z);
	let degrees = vector3.toCartographic().toDegrees();
	let degreesJson = {
		longitude: degrees.longitude,
		latitude: degrees.latitude,
		height: degrees.height,
	};
	cb && cb(degreesJson);
}
export function cameraFlyToGoal(position, orientation, duration = 2, cb = () => {}) {
	let scene = GlobalViewer.scene;
	let camera = scene.mainCamera;
	let cameraController = camera.cameraController();
	position = SSmap.Cartographic.fromDegrees(position.longitude, position.latitude, position.height);
	position = position.toVector3();
	orientation = orientation
		? orientation
		: {
				heading: 0,
				pitch: -90,
				roll: 0,
		  };
	cameraController.flyTo(position, duration, orientation.heading, orientation.pitch, orientation.roll).then(function () {
		cb &&
			cb({
				vector3: {
					x: position.x,
					y: position.y,
					z: position.z,
				},
				orientation: {
					heading: orientation.heading,
					pitch: orientation.pitch,
					roll: orientation.roll,
				},
			});
	});
}
export function getCamera(cb) {
	let cameraCtrl = GlobalViewer.scene.mainCamera.cameraController();
	let degreePosition = cameraCtrl.positionCartographic.toDegrees();
	let degreesJson = {
		longitude: degreePosition.longitude,
		latitude: degreePosition.latitude,
		height: degreePosition.height,
	};
	let orientation = {
		heading: toDegrees(cameraCtrl.heading),
		pitch: toDegrees(cameraCtrl.pitch),
		roll: toDegrees(cameraCtrl.roll),
	};

	function toDegrees(radians) {
		return (180 / Math.PI) * radians;
	}
	cb &&
		cb({
			position: degreesJson,
			orientation,
		});
}

export function changeCameraHeight(point, height) {
	let degrees = SSmap.Cartographic.fromDegrees(point.longitude, point.latitude, point.height).toDegrees();
	degrees.height = degrees.height + height + 3;
	let pointCartographic = SSmap.Cartographic.fromDegrees(degrees.longitude, degrees.latitude, degrees.height).toVector3();
	const camera = window.viewer.scene.mainCamera.cameraController();
	const headings = (180 / Math.PI) * camera.heading;
	const rolls = (180 / Math.PI) * camera.roll;
	let pitchs = (180 / Math.PI) * camera.pitch;
	camera.flyTo(pointCartographic, 0, headings, pitchs, rolls);
}

export function cameraFlyToRectangle(
	boundingBox,
	orientation = {
		heading: 0,
		pitch: -90,
		roll: 0,
	},
	duration = 1
) {
	let cameraController = GlobalViewer.scene.mainCamera.cameraController();
	let ractangle = SSmap.Rectangle.fromDegrees(boundingBox.west, boundingBox.south, boundingBox.east, boundingBox.north);

	cameraController.flyToRectangle(ractangle, duration, orientation.heading, orientation.pitch, orientation.roll);
}

export function getLatlng(rangeList, callback) {
	const result = rangeList.map((i) => {
		return i.map((j) => {
			if (j[0] > -180 && j[0] < 180 && j[1] > -90 && j[1] < 90) {
				return j;
			} else {
				const lnglat = SSmap.Vector3.create(j[0], j[1], j[2]).toCartographic().toDegrees();
				return [lnglat.lon, lnglat.lat, lnglat.height];
			}
		});
	});
	if (typeof callback === 'function') callback(result);
}

export function getCartoFormDegrees(degrees, cb) {
	let carto = SSmap.Cartographic.fromDegrees(degrees.longitude, degrees.latitude, degrees.height);
	cb && cb(JSON.stringify(carto));
}

// 打印ssmap对象
export function log2ssmapObj(obj) {
	let dbo = SSmap.DebugObj.instance();
	dbo.setObj(obj);
	console.log(dbo.className);
	let ppt = dbo.properties;
	console.log(`properties:-------------------------------------------------------------------------`);
	for (let i = 0; i < ppt.length; i++) {
		console.log(ppt[i], `:`, obj[ppt[i]]);
	}
	console.log(`over:-------------------------------------------------------------------------`);
}
